package org.zxp.thread.ccontainer;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: zxp-thread-test
 * @description: 测试ConcurrentHashMap的线程安全性
 * @author: X-Pacific zhang
 * @create: 2019-05-24 13:31
 **/
public class ConcurrentHashMapTest {
    public static void main(String[] args) throws InterruptedException {
        ConcurrentHashMap<Inner,String> map = new ConcurrentHashMap<>();
        //测试线程安全
        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {
                map.put(new Inner(),"");
            }).start();
        }
        Thread.sleep(1000L);
        System.out.println(map.size());//经测试这是线程安全的 结果固定为10000

        HashMap<Inner,String> map2 = new HashMap<>();
        //测试线程安全
        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {
                map2.put(new Inner(),"");
            }).start();
        }
        Thread.sleep(1000L);
        System.out.println(map2.size());//经测试不是线程安全的 结果不固定<=10000
        //因为有可能new Inner()会出现哈希冲突，冲突后，在同一个链表上，可能会丢失一个元素
    }

    static class Inner{

    }
}
